#!/usr/bin/env bash
# Copyright (C) 2014 Julien Bonjean <julien@bonjean.info>
# Copyright (C) 2014 Alexander Keller <github@nycroth.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

#------------------------------------------------------------------------

CARD=$(aplay -l | awk -F \: '/,/{print $2}' | awk '{print $1}' | uniq | head -n 1)

if command -v pulseaudio >/dev/null 2>&1 && pulseaudio --check; then
  # pulseaudio is running, but not all installations use "pulse"
  if amixer -c $CARD -D pulse info >/dev/null 2>&1; then
    MIXER="pulse"
  fi
fi

if [ -n "$(lsmod | grep jack)" ]; then
  MIXER="jackplug"
fi

MIXER=$(amixer info -c $CARD | grep Card | cut -d ' ' -f 2)
MIXER=${MIXER:-default}
SCONTROL="${BLOCK_INSTANCE:-$(
  amixer -c $CARD -D $MIXER scontrols |
    sed -n "s/Simple mixer control '\([^']*\)',0/\1/p" |
    head -n1
)}"

# The first parameter sets the step to change the volume by (and units to display)
# This may be in in % or dB (eg. 5% or 3dB)
if [[ -z "$STEP" ]]; then
  STEP="${1:-5%}"
fi

#------------------------------------------------------------------------

capability() { # Return "Capture" if the device is a capture device
  amixer -c $CARD -D $MIXER get $SCONTROL |
    sed -n "s/  Capabilities:.*cvolume.*/Capture/p"
}

volume() {
  amixer -c $CARD -D $MIXER get $SCONTROL $(capability)
}

format() {

  perl_filter='if (/.*\[(\d+%)\] (\[(-?\d+.\d+dB)\] )?\[(on|off)\]/)'
  perl_filter+='{CORE::say $4 eq "off" ? "MUTE" : "'
  # If dB was selected, print that instead
  perl_filter+=$([[ $STEP = *dB ]] && echo '$3' || echo '$1')
  perl_filter+='"; exit}'
  output=$(perl -ne "$perl_filter")
  echo "$LABEL$output"
}

#------------------------------------------------------------------------

case $BLOCK_BUTTON in
3) amixer -q -c $CARD -D $MIXER sset $SCONTROL $(capability) toggle ;;          # right click, mute/unmute
4) amixer -q -c $CARD -D $MIXER sset $SCONTROL $(capability) ${STEP}+ unmute ;; # scroll up, increase
5) amixer -q -c $CARD -D $MIXER sset $SCONTROL $(capability) ${STEP}- unmute ;; # scroll down, decrease
esac

volume | format
